import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:get/get.dart';
import 'package:lifecycle_lite/life_navigator_observer.dart';
import 'package:tencent_calls_uikit/tuicall_kit.dart';
import 'package:xiaofanshu_flutter/controller/websocket_controller.dart';
import 'package:xiaofanshu_flutter/pages/auth/login.dart';
import 'package:xiaofanshu_flutter/pages/home/home.dart';
import 'package:xiaofanshu_flutter/utils/Adapt.dart';
import 'package:xiaofanshu_flutter/utils/store_util.dart';
import 'package:xiaofanshu_flutter/utils/app_state_manager.dart';
import 'package:xiaofanshu_flutter/utils/guide_service.dart';
import 'package:xiaofanshu_flutter/utils/app_update_util.dart';

import 'bindings/controller_binding.dart';
import 'config/routes.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _setupMemoryPressureListener();
  }

  /// 设置内存压力监听
  void _setupMemoryPressureListener() {
    // 监听系统内存压力警告
    SystemChannels.platform.setMethodCallHandler((call) async {
      if (call.method == 'System.requestAppExit') {
        Get.log('System requesting app exit - saving state');
        // await AppStateManager.saveAppState();
      }
    });
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    Get.log('App lifecycle state changed to: $state');
    
    switch (state) {
      case AppLifecycleState.resumed:
        _onAppResumed();
        break;
      case AppLifecycleState.paused:
        _onAppPaused();
        break;
      case AppLifecycleState.detached:
        _onAppDetached();
        break;
      case AppLifecycleState.inactive:
        _onAppInactive();
        break;
      case AppLifecycleState.hidden:
        _onAppHidden();
        break;
    }
  }

  void _onAppResumed() {
    Get.log('App resumed - checking app state');
    
    // 应用回到前台时，检查是否需要重新初始化
    _checkAndRestoreAppState();
  }

  void _onAppPaused() {
    Get.log('App paused - not saving state (normal background)');
    
    // 应用进入后台时不保存状态，这是正常情况
    // 只有在应用真正要被销毁时才保存状态
  }

  void _onAppInactive() {
    Get.log('App inactive - not saving state');
    
    // 应用不活跃状态（如接听电话、通知栏下拉等）不保存状态
  }

  void _onAppHidden() {
    Get.log('App hidden - not saving state');
    
    // 应用被隐藏时不保存状态
  }

  void _onAppDetached() {
    Get.log('App detached - saving app state before termination');
    
    // 应用即将被终止时才保存状态
    // 这是应用真正要被销毁的信号
    // AppStateManager.saveAppState();
  }

  void _checkAndRestoreAppState() {
    Future.delayed(const Duration(milliseconds: 200), () async {
      try {
        // 检查应用是否可能被回收过
        bool wasRecycled = await AppStateManager.wasAppRecycled();
        if (wasRecycled) {
          Get.log('App appears to have been recycled, attempting restore');
          
          // 尝试恢复应用状态
          // bool restored = await AppStateManager.restoreAppState();
          // if (!restored) {
          //   Get.log('Failed to restore app state, continuing with normal flow');
          // }
        }
      } catch (e) {
        Get.log('Error during app state check: $e');
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    Adapt.initialize(context);
    return GetMaterialApp(
      localizationsDelegates: const [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: const [
        Locale('zh', 'CN'),
        Locale('en', 'US'),
      ],
      navigatorObservers: [
        LifeNavigatorObserver(),
        TUICallKit.navigatorObserver,
        AppStateNavigatorObserver(),
      ],
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        scaffoldBackgroundColor: Colors.white,
        splashColor: Colors.transparent,
        highlightColor: Colors.transparent,
        tabBarTheme: const TabBarTheme(dividerColor: Colors.transparent),
        buttonTheme: const ButtonThemeData(
          splashColor: Colors.transparent,
          highlightColor: Colors.transparent,
        ),
      ),
      getPages: RouteConfig.routes,
      defaultTransition: Transition.rightToLeft,
      builder: EasyLoading.init(),
      initialBinding: ControllerBinding(),
      home: const InitializationPage(),
    );
  }
}

class InitializationPage extends StatefulWidget {
  const InitializationPage({super.key});

  @override
  State<InitializationPage> createState() => _InitializationPageState();
}

class _InitializationPageState extends State<InitializationPage>
    with SingleTickerProviderStateMixin {
  WebsocketController websocketController =
      Get.put(WebsocketController(), permanent: true);

  late AnimationController _animationController;
  late Animation<double> _fadeAnimation;
  late Animation<double> _scaleAnimation;
  late Animation<Offset> _slideAnimation;

  @override
  void initState() {
    super.initState();
    
    // 初始化动画控制器
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 1500),
      vsync: this,
    );
    
    // 淡入动画
    _fadeAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: const Interval(0.0, 0.6, curve: Curves.easeOut),
    ));
    
    // 缩放动画
    _scaleAnimation = Tween<double>(
      begin: 0.5,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: const Interval(0.0, 0.6, curve: Curves.easeOutBack),
    ));
    
    // 滑入动画
    _slideAnimation = Tween<Offset>(
      begin: const Offset(0, 0.3),
      end: Offset.zero,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: const Interval(0.3, 0.8, curve: Curves.easeOut),
    ));
    
    // 启动初始化
    _initializeApp();
  }

  /// 初始化应用
  Future<void> _initializeApp() async {
    // 启动动画
    _animationController.forward();
    
    // 等待 2.5 秒
    await Future.delayed(const Duration(milliseconds: 2500));
    
    // 检查登录状态
    String? token = await readData('token');
    
    // ========== 修改：无条件创建 GuideController ==========
    // 始终创建 GuideController，确保子页面能找到它
    try {
      Get.find<GuideController>();
      Get.log('✅ GuideController 已存在');
    } catch (e) {
      // 如果不存在，创建新的
      final guideController = Get.put(GuideController(), permanent: true);
      Get.log('✅ 创建新的 GuideController');
      
      // 检查是否是首次启动
      bool isFirstLaunch = await GuideService.isFirstLaunch();
      
      // 如果是首次启动且已登录，初始化引导流程
      if (isFirstLaunch && token != null && token.isNotEmpty) {
        await guideController.startGuideFlow();
        Get.log('✅ 引导流程已初始化');
      }
    }
    // ====================================================
    
    // 跳转到对应页面
    if (token != null && token.isNotEmpty) {
      Get.offAllNamed('/home');
      
      // ========== 检查应用更新 ==========
      // 登录后延迟检查更新，避免干扰引导流程
      Future.delayed(const Duration(seconds: 2), () {
        AppUpdateUtil.checkUpdate();
      });
      // =================================
    } else {
      Get.offAllNamed('/login');
    }
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: [
              Color(0xFF6366F1), // 靛蓝色
              Color(0xFF8B5CF6), // 紫色
              Color(0xFFEC4899), // 粉色
            ],
          ),
        ),
        child: AnimatedBuilder(
          animation: _animationController,
          builder: (context, child) {
            return Stack(
              children: [
                // 主内容区域
                Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      // Logo 图标（带缩放和淡入动画）
                      FadeTransition(
                        opacity: _fadeAnimation,
                        child: ScaleTransition(
                          scale: _scaleAnimation,
                          child: Container(
                            width: 150,
                            height: 150,
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(30),
                              boxShadow: [
                                BoxShadow(
                                  color: Colors.black.withOpacity(0.2),
                                  blurRadius: 30,
                                  offset: const Offset(0, 15),
                                ),
                              ],
                            ),
                            child: Stack(
                              alignment: Alignment.center,
                              children: [
                                // 自定义图片
                                ClipRRect(
                                  borderRadius: BorderRadius.circular(30),
                                  child: Image.asset(
                                    'images/kaiping.png',
                                    width: 150,
                                    height: 150,
                                    fit: BoxFit.cover,
                                    errorBuilder: (context, error, stackTrace) {
                                      // 图片加载失败时显示默认图标
                                      return const Icon(
                                        Icons.auto_stories,
                                        size: 60,
                                        color: Color(0xFF6366F1),
                                      );
                                    },
                                  ),
                                ),
                                // AI 图标徽章（右上角）
                                Positioned(
                                  right: 5,
                                  top: 5,
                                  child: Container(
                                    padding: const EdgeInsets.all(8),
                                    decoration: BoxDecoration(
                                      color: const Color(0xFFEC4899),
                                      shape: BoxShape.circle,
                                      boxShadow: [
                                        BoxShadow(
                                          color: Colors.black.withOpacity(0.2),
                                          blurRadius: 8,
                                          offset: const Offset(0, 2),
                                        ),
                                      ],
                                    ),
                                    child: const Icon(
                                      Icons.psychology,
                                      size: 18,
                                      color: Colors.white,
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                      
                      const SizedBox(height: 30),
                      
                      // 应用名称（带滑入和淡入动画）
                      SlideTransition(
                        position: _slideAnimation,
                        child: FadeTransition(
                          opacity: _fadeAnimation,
                          child: const Text(
                            '故事地图',
                            style: TextStyle(
                              fontSize: 42,
                              fontWeight: FontWeight.bold,
                              color: Colors.white,
                              letterSpacing: 2,
                              shadows: [
                                Shadow(
                                  color: Colors.black26,
                                  offset: Offset(0, 2),
                                  blurRadius: 4,
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                      
                      const SizedBox(height: 16),
                      
                      // 标语（带延迟淡入）
                      FadeTransition(
                        opacity: Tween<double>(
                          begin: 0.0,
                          end: 0.9,
                        ).animate(CurvedAnimation(
                          parent: _animationController,
                          curve: const Interval(0.5, 1.0, curve: Curves.easeIn),
                        )),
                        child: Container(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 24,
                            vertical: 8,
                          ),
                          decoration: BoxDecoration(
                            color: Colors.white.withOpacity(0.15),
                            borderRadius: BorderRadius.circular(20),
                          ),
                          child: const Text(
                            '分享故事 · 智能对话 · 探索世界',
                            style: TextStyle(
                              fontSize: 15,
                              color: Colors.white,
                              letterSpacing: 1,
                              fontWeight: FontWeight.w300,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                
                // 底部版本信息
                Positioned(
                  bottom: 50,
                  left: 0,
                  right: 0,
                  child: FadeTransition(
                    opacity: Tween<double>(
                      begin: 0.0,
                      end: 0.6,
                    ).animate(CurvedAnimation(
                      parent: _animationController,
                      curve: const Interval(0.7, 1.0, curve: Curves.easeIn),
                    )),
                    child: const Column(
                      children: [
                        // 加载动画
                        SizedBox(
                          width: 30,
                          height: 30,
                          child: CircularProgressIndicator(
                            strokeWidth: 2,
                            valueColor: AlwaysStoppedAnimation<Color>(
                              Colors.white,
                            ),
                          ),
                        ),
                        SizedBox(height: 16),
                        Text(
                          '正在加载精彩内容...',
                          style: TextStyle(
                            fontSize: 13,
                            color: Colors.white70,
                            letterSpacing: 0.5,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            );
          },
        ),
      ),
    );
  }
}

/// 路由观察器，用于自动保存应用状态
class AppStateNavigatorObserver extends NavigatorObserver {
  @override
  void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
    super.didPush(route, previousRoute);
    _saveStateAfterNavigation();
  }

  @override
  void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) {
    super.didReplace(newRoute: newRoute, oldRoute: oldRoute);
    _saveStateAfterNavigation();
  }

  @override
  void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
    super.didPop(route, previousRoute);
    _saveStateAfterNavigation();
  }

  void _saveStateAfterNavigation() {
    // 延迟保存，确保路由变更完成
    Future.delayed(const Duration(milliseconds: 500), () {
      // AppStateManager.saveAppState();
    });
  }
}
